package com.basic.shiro.handlers;

import com.basic.shiro.services.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/shiro")
public class ShiroHandler {

    @Autowired
    private ShiroService shiroService;

    @RequestMapping("/testShiroAnnotation")
    private String testShiroAnnotation(){
        shiroService.testMethod();
        return "redirect:/list.jsp";
    }
    @RequestMapping("/login")
    public String login(@RequestParam("username") String username
            , @RequestParam("password") String password) {
        /*1.获取当前的subject*/
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
            // 把用户名和密码封装为 UsernamePasswordToken 对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            // rememberme
            token.setRememberMe(true);
            try {
                // 执行登录. 到shiroRealm中的doGetAuthenticationInfo(AuthenticationToken token)
                currentUser.login(token);
            }

            catch (AuthenticationException ae) {
                //unexpected condition?  error?
                System.out.println("登录失败"+"username: = [" + username + "], password: = [" + password + "]");
            }
        }


        return "redirect:/list.jsp";
    }
}
